#include "languagemodel.h"

LanguageModel::LanguageModel(QObject *parent)
    : QAbstractListModel(parent)
{
    QHash<int, QByteArray> roles;

    roles[RoleLanguageName]="name";
    roles[RoleId]="id";
    roles[RoleChosen]="chosen";

    setRoleNames(roles);
}

void LanguageModel::addLanguage(const Jezik &jezik){
    beginInsertRows(QModelIndex(), rowCount(), rowCount());
    m_languageItems << new LanguageItem(jezik.dajId(), jezik.dajImeJezika(), jezik.jeOdabran(), rowCount());

    connect(m_languageItems.last(), SIGNAL(dataChanged()), SLOT(handleItemChange()));

    qDebug()<<"dodajem jezik"<<jezik.dajImeJezika();
    endInsertRows();
    emit countChanged(m_languageItems.count());
}

int LanguageModel::rowCount(const QModelIndex & parent) const  {
    return m_languageItems.count();
}

int LanguageModel::count(){
    return m_languageItems.count();
}

void LanguageModel::clear(){
    int currentCount=m_languageItems.count();
    for (int i=0; i<currentCount; i++)
    {
        beginRemoveRows(QModelIndex(), 0, 0);

        LanguageItem* item=m_languageItems.takeFirst();
        delete item;

        emit countChanged(m_languageItems.count());
        endRemoveRows();
    }
}

LanguageItem* LanguageModel::get(int index){
    return m_languageItems[index];
}

QVariant LanguageModel::data(const QModelIndex & index, int role) const  {
    if (index.row() < 0 || index.row() > m_languageItems.count())
        return QVariant();

    LanguageItem* language=m_languageItems[index.row()];

    if (role == RoleLanguageName)
        return language->name();
    else if (role == RoleChosen)
        return language->odabran();
    else if (role == RoleId)
        return language->idJezika();

    return QVariant();
}

QModelIndex LanguageModel::indexFromItem(const LanguageItem *item) const
{
    Q_ASSERT(item);
    for(int row=0; row<m_languageItems.size(); ++row) {
        if(m_languageItems.at(row) == item) return index(row);
    }
    return QModelIndex();
}

void LanguageModel::handleItemChange()
{
    LanguageItem* item = static_cast<LanguageItem*>(sender());
    QModelIndex index = indexFromItem(item);
    if(index.isValid())
        emit dataChanged(index, index);
}
